/* 
Colorful agnostic calendar - implementation of agnostic_calendar with new features
*/

/*
New global functions
*/
activateColor = function(dayDivElement, sColor) {
    if (dayDivElement.hasClassName('cell'))
        dayDivElement.removeClassName('cell');
    if (!dayDivElement.hasClassName('cellavail'))
        dayDivElement.addClassName('cellavail');
        
    $(dayDivElement).setStyle({ backgroundColor: sColor });
}

deactivateColor = function(dayDivElement) {
    $(dayDivElement).setStyle({ backgroundColor: '' });
    if (dayDivElement.hasClassName('cellavail'))
        dayDivElement.removeClassName('cellavail');
    if (!dayDivElement.hasClassName('cell'))
        dayDivElement.addClassName('cell');
}
		

/* 
    Sets color for different ranges, initilizes this.ranges array
    ranges - array of date ranges, can be comma-delimited list
    clr - color for set
    rangeNames - names of ranges, array of strings or commma-delimited list; 
                 if number of names lesser number of ranges then all rest ranges will have last range name for range name list
*/
AgnosticCalendar.prototype.paintSetColor = function(ranges, clr, rangeName) {
    if (this.editEnabled) {
        if (!(ranges instanceof Array)) {
            ranges = ranges.split(",");
        }
        var indexes = this.dateRangesToIndexes(ranges);
        var iRange = 0;
        for (var key in indexes) {
            var index = indexes[key];
            var element = this.controlMap[index];
            activateColor(element, clr);
            setRangeName(element, rangeName);
            iRange++;
        }
    }
}

// Deactivates ranges activated with color
AgnosticCalendar.prototype.deactivateRangesColor = function(ranges) {
    if (this.editEnabled) {

        if (!(ranges instanceof Array)) {
            ranges = ranges.split(",");
        }

        var indexes = this.dateRangesToIndexes(ranges);
        for (var key in indexes) {
            var index = indexes[key];
            var element = this.$(this.lookupMap[index]);
            deactivateColor(element);
            clearRangeName(element);
        }
    }
}

// Returns first index in every range
AgnosticCalendar.prototype.getRangeFirstIndexes = function(arrayDateIndexes) {
    var retRanges = new Array();
    var numRanges = 0;
    var previous = arrayDateIndexes[0];
    var currentFirstInRange = arrayDateIndexes[0];
    var next; // the index
    for (var ii = 1; ii <= arrayDateIndexes.length; ii++) {
        next = arrayDateIndexes[ii];
        var ctrlPrev = this.controlMap[previous];
        var ctrlNext = this.controlMap[next];

        if (previous + 1 == next &&
		            ctrlPrev.style.backgroundColor == ctrlNext.style.backgroundColor &&
		            getRangeName(ctrlPrev) === getRangeName(ctrlNext)) {
            // this is part of an ongoing series
        }
        else {
            retRanges[numRanges] = currentFirstInRange;
            currentFirstInRange = next;
            numRanges++;
        }
        previous = next;
    }
    // one last time for the last range:
    if (next > currentFirstInRange) {
        // the previous number was the last in a range a range
        numRanges++;
        retRanges[numRanges] = currentFirstInRange;

    }
    return retRanges;
}

// Returns first indexes of all ranges what has name rangeName
AgnosticCalendar.prototype.getRange = function(rangeName) {
    var selected = this.getSelectedIndexes();
    var ranges = this.getRangeFirstIndexes(selected);
    for (var iRange = 0; iRange < ranges.length; iRange++) {
        if ( this.getRangeName(this.controlMap[ranges[iRange]]) === rangeName) {
            res.push(ranges[iRange]);
        }
    }
    return res;
}

//  Returns color of the first range with name rangeName
AgnosticCalendar.prototype.getColor = function(rangeName) {
    var selected = this.getSelectedIndexes();
    var ranges = this.getRangeFirstIndexes(selected);
    var res = '#00FF00';
    for (var iRange = 0; iRange < ranges.length; iRange++) {
        if (this.getRangeName(this.controlMap[ranges[iRange]]) === rangeName) {
            res = this.controlMap[ranges[iRange]].style.backgroundColor;
        }
    }
    return res;
}

// Item of range group, that is all ranges with same range name and color
function RangeGroupItem(title, color) {
    this.title = title;
    this.color = color;
    this.rangeStrings = new Array();
}

// Returns true if title and color are indentical with paramerters
RangeGroupItem.prototype.compare = function(title, color) {
    return title === this.title && color === this.color;
}

// Add new string to rangeTexts
RangeGroupItem.prototype.addRange = function(rangeText) {
    this.rangeStrings.push(rangeText);
}

// Collects all ranges and groups them by Range name + colors
// Returns array of RangeGroupItem elements
AgnosticCalendar.prototype.groupSelectedRanges = function() {
    var groups = new Array();
    var selected = this.getSelectedIndexes();
    var rangeTexts = this.dateIndexesToRanges(selected);
    var rangeInds = this.getRangeFirstIndexes(selected);
    if (rangeTexts.length > 0) {
        for (var ind = 0; ind < rangeTexts.length; ind++) {
            // obtain color of this range
            var color = (ind < rangeInds.length ? this.controlMap[rangeInds[ind]].style.backgroundColor : null);
            if (!color) color = '#00FF00';
            var rangeName = null;
            if (ind < rangeInds.length) {
                var ctrl = this.controlMap[rangeInds[ind]];
                if (ctrl) {
                    Element.extend(ctrl);
                    rangeName = getRangeName(ctrl);
                }
            }

            // obtain rangeName
            if (!rangeName) rangeName = '';

            // find/create group
            var groupFound = false;
            for (var indGrp = 0; indGrp < groups.length; indGrp++) {
                if (groups[indGrp].compare(rangeName, color)) {
                    groups[indGrp].addRange(this.rangeToString(rangeTexts[ind]));
                    groupFound = true;
                }
            }
            if (!groupFound) {
                var newGroup = new RangeGroupItem(rangeName, color);
                newGroup.addRange(this.rangeToString(rangeTexts[ind]));
                groups.push(newGroup);
            }
        }
    }
    return groups;
}

// Return HTML for legend HTML
AgnosticCalendar.prototype.getLegendHTML = function() {
    var text = '';
    var groups = this.groupSelectedRanges();
    if (groups.length) {
        text = '<table border="0">'
        for (var indGrp = 0; indGrp < groups.length; indGrp++) {
            var grp = groups[indGrp];
            text += '<tr><td width="25px"><div style="width: 25px; border-width: 2px; border-style: solid; background-color: ' +
                    grp.color +
                    ';">&nbsp;</div></td><td align="left">' +
                    grp.title +
                    '</td><td align = "left"></tr>';
            for (var indTxt = 0; indTxt < grp.rangeStrings.length; indTxt++) {
                text += '<tr><td colspan="2" align="left">' + grp.rangeStrings[indTxt] + '</td></tr>';
            }
        }
        text += '</table>';
    }
    return text;
}

// Enables or disables editing
AgnosticCalendar.prototype.enableEdit = function(enable) {
    this.editEnabled = enable;
}

// Place legend on the top, left, right or bottom depends on 'where'
AgnosticCalendar.prototype.placeLegend = function(where) {
    var name = 'legend_' + where;
    var els = this.agc.getElementsByTagName('div');
    for (var ind = 0; ind < els.length; ind++) {
        var el = els[ind];
        if (el.id === name) {
            el.innerHTML = this.getLegendHTML();
        }
    }
}

// Clears legend from "where"
AgnosticCalendar.prototype.clearLegend = function(where) {
    var name = 'legend_' + where;
    var els = this.agc.getElementsByTagName('div');
    for (var ind = 0; ind < els.length; ind++) {
        var el = els[ind];
        if (el.id === name) {
            el.innerHTML = '';
        }
    }
}

// Clears all "legends"
AgnosticCalendar.prototype.clearLegendAll = function() {
    this.clearLegend("top");
    this.clearLegend("bottom");
    this.clearLegend("left");
    this.clearLegend("right");
}


